<template>
  <page-wrap>
 
  <div class="container">
      <video id="video"></video>
      <div v-if="mask" class="mask"></div>
  </div>
  <h4>识别到的信息：<span style="color: red;">{{ message }}</span></h4>
  <button @click="scanner">扫码</button>&nbsp;
  <button @click="close">关闭</button>&nbsp;
</page-wrap>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { BrowserMultiFormatReader } from '@zxing/library';

let message = ref('');
let codeReader = null;
let selectedDeviceId = '';
let mask = ref(false);

function init() {
  // 识别和处理多种常见的条形码和二维码格式
  codeReader = new BrowserMultiFormatReader();
  // 获取当前设备上可用的视频输入设备列表
  codeReader.getVideoInputDevices().then(videoInputDevices => {
      if (videoInputDevices.length > 1) {
          // 后缀摄像头（手机）
          selectedDeviceId = videoInputDevices[1].deviceId;
      }else {
          // 前置摄像头
          selectedDeviceId = videoInputDevices[0].deviceId;
      }
  })
}

onMounted(() => {
  init();
})

function scanner() {
  mask.value = true
  // 自动打开指定的视频输入设备，并实时对视频流中的每一帧图像进行条形码和二维码的解码操作，此方法不是只进行一次解码尝试，而是在视频流持续传输的过程中，不断地对每一帧图像进行解码分析
  codeReader.decodeFromVideoDevice(selectedDeviceId, 'video', (result, err) => {
      if (result) {
          message.value = result.text;
      }
      if (err) {}
  })
}
function close() {
  codeReader.reset();
  message.value = '';
  mask.value = false;
}
</script>

<style>
.container {
  width: 100%;
  height: 60vh;
  position: relative;
  margin-top: 10px;
  overflow: hidden;
}
.container > video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.mask {
  position: absolute;
  left: 15%;
  top: 20%;
  max-width: 100%;
  width: 70%;
  height: 60%;
  border-radius: 2px;
  outline: rgba(0, 0, 0, .25) solid 20vmax;
}
</style>